//
//  DeviceManagerViewController.m
//  Router
//
//  Created by teki on 15/10/13.
//  Copyright © 2015年 dc. All rights reserved.
//

#import "DeviceManagerViewController.h"
#import "DeviceManagerHeaderView.h"
#import "DeviceManagerTableViewCell.h"
#import "BlackListTableViewCell.h"
#import "DiscoverNewWIFIController.h"

#import "MJRefresh.h"
#import "TKDIYHeader.h"

#import "DeviceManagerHelper.h"
#import "DeviceInfoModel.h"
#import "UserHelper.h"

@interface DeviceManagerViewController ()
//@property (nonatomic, strong) DeviceManagerHeaderView *headerView;

@property (nonatomic, strong) UISegmentedControl *control;

@property (nonatomic, strong) NSMutableArray *deviceList;
@property (nonatomic, strong) NSMutableArray *blackList; ///< 黑名单

@property (nonatomic, strong) DeviceManagerHelper *deviceHelper;
@property (nonatomic, strong) UserHelper *userHelper;
@end

@implementation DeviceManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = RGB(226, 244, 222);
    self.tableView.backgroundColor = RGB(226, 244, 222);
    
    self.control = [[UISegmentedControl alloc] initWithItems:@[@"设备管理",@"黑名单"]];
    self.control.selectedSegmentIndex = 0;
    self.control.backgroundColor = NavgationBarBackgroundColor;
    self.control.tintColor = [UIColor whiteColor];
    [self.control addTarget:self action:@selector(segementValueChanged:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = self.control;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"BlackListTableViewCell" bundle:nil] forCellReuseIdentifier:@"BlackListTableViewCell"];
    
    [self.tableView registerClass:[DeviceManagerTableViewCell class] forCellReuseIdentifier:@"DeviceManagerTableViewCell"];
    
    self.tableView.separatorColor = SeparatorLineColor;
    self.tableView.tableFooterView = [UIView new];
    

    self.tableView.mj_header = [TKDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.tableView.mj_header beginRefreshing];
    


    
    // Do any additional setup after loading the view.
}

//清除数据
-(void)clearData
{
    self.deviceList = [NSMutableArray array];
    self.blackList = [NSMutableArray array];
}


- (void)findNewWIFINotification:(NSNotification *)notify
{
    BOOL hasNewWIFI = [[notify object] boolValue];
    if (hasNewWIFI) {
        [self addLeftBarButtonWithNormalImageName:@"home_location" selectedImageName:@"home_location_pre" target:self action:@selector(leftButtonPressed:)];
    }
    self.navigationItem.leftBarButtonItem.customView.hidden = !hasNewWIFI;

}


- (void)leftButtonPressed:(id)sender
{
    NSLog(@"___func:%s__",__func__);
    DiscoverNewWIFIController *discoverNewWIFI = [[DiscoverNewWIFIController alloc] init];
    discoverNewWIFI.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:discoverNewWIFI animated:YES];

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TK_FindNewWIFINotification object:nil];
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findNewWIFINotification:) name:TK_FindNewWIFINotification object:nil];
    
    [self segementValueChanged:self.control];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)loadNewData
{
    if (self.control.selectedSegmentIndex == 0)
    {
        [self refreshDeviceList];
    }
    else{
        [self refreshBlackList];
    }
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.control.selectedSegmentIndex == 0)
    {
        return [self.deviceList count];
    }
    else{
        return [self.blackList count];
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.control.selectedSegmentIndex == 0)
    {
        DeviceManagerTableViewCell *cell = (DeviceManagerTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"DeviceManagerTableViewCell" forIndexPath:indexPath];
        cell.model = self.deviceList[indexPath.row];
        WEAKSELF
        [cell setAddToBlackListBlock:^(DeviceInfoModel *model) {
            [weakSelf addToBlackListWithDeviceModel:model];
        }];
        return cell;

    }
    else
    {
        BlackListTableViewCell *cell = (BlackListTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"BlackListTableViewCell" forIndexPath:indexPath];
        cell.model = self.blackList[indexPath.row];
        WEAKSELF
        [cell setMoveFromBlackListBlock:^(DeviceInfoModel *model) {
            [weakSelf removeFromBlackListWithDeviceModel:model];
        }];
        return cell;
    }

}


#pragma mark -
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (self.control.selectedSegmentIndex == 0 ) {
        return 74.0f;
    }
    else{
        return 44.0f;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}




// 设置分隔线 iOS8 下才起作用
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 18, 0, 18)];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0, 18, 0, 18)];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 18, 0, 18)];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 18, 0, 18)];
    }
}



- (void)segementValueChanged:(UISegmentedControl *)control
{
    
    if (control.selectedSegmentIndex == 0)
    {
        if ([self.deviceList count] == 0)
        {
            [self.tableView.mj_header beginRefreshing];
//            [self refreshDeviceList];
        }
        else
        {
            [self.tableView reloadData];
        }
    }
    else
    {
        if ([self.blackList count] == 0)
        {
//            [self refreshBlackList];
            [self.tableView.mj_header beginRefreshing];
        }
        else
        {
            [self.tableView reloadData];
        }
    }
}



//- (DeviceManagerHeaderView *)headerView
//{
//    if (_headerView == nil )
//    {
//        _headerView = [[DeviceManagerHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 120)];
//    }
//    return _headerView;
//}

#pragma mark -
#pragma mark   Requests
- (void)refreshDeviceList
{
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    UserModel *user = [UserSingleton shareInstance].userModel.user[0];
    self.activity = [self startActivityWithTitle:@""];
    WEAKSELF
    [self.deviceHelper getConnectedDeviceListWithDeviceID:wifi.device_id user:user.userName success:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf stopActivityWithActivity:strongSelf.activity title:@""];
        [strongSelf.tableView.mj_header endRefreshing];
        if (responseObject)
        {
            NSString *deviceStatus = responseObject[@"deviceStatus"];
            if ([deviceStatus isEqualToString:@"online"])
            {
                NSMutableArray *array = [DeviceInfoModel objectArrayWithKeyValuesArray:responseObject[@"connectedDeviceList"]];
                strongSelf.deviceList = array;
                [strongSelf.tableView reloadData];
            }
            else
            {
                [strongSelf showOffLineView];
            }
        }
        
    } failure:^(NSError *error) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.tableView.mj_header endRefreshing];
        NSString *failedReason = [error localizedDescription];
        [strongSelf stopActivityWithActivity:strongSelf.activity title:failedReason];
    }];
}


///
- (void)refreshBlackList
{
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    UserModel *user = [UserSingleton shareInstance].userModel.user[0];
    
    self.activity = [self startActivityWithTitle:@""];
    WEAKSELF
    
    [self.deviceHelper getBlackListByDeviceID:wifi.device_id user:user.userName success:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf stopActivityWithActivity:strongSelf.activity title:@""];
        [strongSelf.tableView.mj_header endRefreshing];
        
        if (responseObject)
        {
            NSString *deviceStatus = responseObject[@"deviceStatus"];
            if ([deviceStatus isEqualToString:@"online"])
            {
                NSMutableArray *array = [DeviceInfoModel objectArrayWithKeyValuesArray:responseObject[@"blackList"]];
                strongSelf.blackList = [NSMutableArray arrayWithArray:array];
                [strongSelf.tableView reloadData];
            }
            else{
                [strongSelf showOffLineView];
            }
        }
    } failure:^(NSError *error) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.tableView.mj_header endRefreshing];
        NSString *failedReason = [error localizedDescription];
        [strongSelf stopActivityWithActivity:strongSelf.activity title:failedReason];
    }];
}



- (void)addToBlackListWithDeviceModel:(DeviceInfoModel *)model
{
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    if (wifi && model) {
        self.activity = [self startActivityWithTitle:@"正在拉黑..."];
        WEAKSELF
        [self.deviceHelper addToBlackListByMacWithDeviceID:wifi.device_id mac:model.hwaddr hostName:model.hostname success:^(BOOL succ, id responseObject, NSString *msg) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            [strongSelf stopActivityWithActivity:strongSelf.activity title:@""];
            NSString *deviceStatus = responseObject[@"deviceStatus"];
            if (deviceStatus&& [deviceStatus isEqualToString:@"online"]) {
                strongSelf.deviceList =  [DeviceInfoModel objectArrayWithKeyValuesArray:responseObject[@"connectedDeviceList"]];
                [strongSelf.tableView reloadData];
            }
        } failure:^(NSError *error) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            NSString *failedReason = [error localizedDescription];
            [strongSelf stopActivityWithActivity:strongSelf.activity title:failedReason];
        }];
    }

}



- (void)removeFromBlackListWithDeviceModel:(DeviceInfoModel *)model
{
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    if (wifi && model) {
        self.activity = [self startActivityWithTitle:@"正在恢复..."];
        WEAKSELF
        [self.deviceHelper  deleteFromBlackListWithDeviceID:wifi.device_id mac:model.hwaddr success:^(BOOL succ, id responseObject, NSString *msg) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            [strongSelf stopActivityWithActivity:strongSelf.activity title:@""];
            NSString *deviceStatus = responseObject[@"deviceStatus"];
            if (deviceStatus&& [deviceStatus isEqualToString:@"online"]) {
                strongSelf.blackList =  [DeviceInfoModel objectArrayWithKeyValuesArray:responseObject[@"blackList"]];
                [strongSelf.tableView reloadData];
            }
        } failure:^(NSError *error) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            NSString *failedReason = [error localizedDescription];
            [strongSelf stopActivityWithActivity:strongSelf.activity title:failedReason];
        }];
    }
}

- (void)showOffLineView
{
    WEAKSELF
    [self showNetworkExceptionWithView:self.view andTitle:@"连不上网络了!" andButtonTitle:@"点击重试" andBtnBlock:^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf loginRequest];
    }];
}


- (void)loginRequest
{
    UserModel *user = [UserSingleton shareInstance].userModel.user[0];
    NSString *phone = user.userName;
    NSString *password = [UserSingleton shareInstance].password;
    
    
    self.activity = [self startActivityWithTitle:@"正在重试,请稍候..."];
    WEAKSELF
    [self.userHelper loginWithPhone:phone password:password success:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (succ) {
            [strongSelf stopActivityWithActivity:strongSelf.activity title:nil];
            LoginResponseModel *model = (LoginResponseModel *)responseObject;
            UserSingleton *singleton = [UserSingleton shareInstance];
            singleton.userModel = model;
            [singleton saveData];
            if ([model.wifi.status isEqualToString:@"offline"]) {
                [strongSelf showOffLineView];
            }
        }
        else{
            [strongSelf stopActivityWithActivity:strongSelf.activity title:nil];
            [strongSelf showOffLineView];
        }
    } failure:^(NSError *error) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf stopActivityWithActivity:strongSelf.activity title:@""];
        [strongSelf showOffLineView];
    }];
}

#pragma mark -
#pragma mark    setters and getters
- (DeviceManagerHelper *)deviceHelper
{
    if (!_deviceHelper)
    {
        _deviceHelper = [[DeviceManagerHelper alloc] init];
    }
    return _deviceHelper;

}


- (UserHelper *)userHelper
{
    if (!_userHelper) {
        _userHelper = [[UserHelper alloc] init];
    }
    return _userHelper;
}

@end
